package com.example.springblog.controller;

import com.example.springblog.constant.Constants;
import com.example.springblog.model.Result;
import com.example.springblog.model.UserInfo;
import com.example.springblog.service.UserInfoService;
import com.example.springblog.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * Description:
 * Date: 2024-08-26
 * Time: 17:52
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserInfoController {
    @Autowired
    private UserInfoService userInfoService;

    @RequestMapping("/login")
    public Result login(String userName,String password) {
        log.info("UserInfoController#login 接收参数：userName:{},password:{}",userName,password);
        //1.校验参数合法性
        if(!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            return Result.fail("账号或密码不能为空");
        }
        //2.校验密码是否正确
        //从数据库中查找用户
        UserInfo userInfo = userInfoService.selectByName(userName);
        //用户不存在
        if(userInfo == null) {
            log.error("用户不存在");
            return Result.fail("用户不存在");
        }
        //密码错误
        if(!password.equals(userInfo.getPassword())) {
            log.error("密码错误");
            return Result.fail("密码错误");

        }
        //3.若密码正确，则返回 token，反之则返回错误信息
        Map<String,Object> claim = new HashMap<>();
        claim.put(Constants.TOKEN_ID,userInfo.getId());
        claim.put(Constants.TOKEN_USERNAME,userInfo.getUserName());
        String token = JwtUtils.genJwtToken(claim);
        log.info("UserController#login 返回结果token:{}",token);
        return Result.success(token);
    }

    /**
     * 获取当前登录用户的信息
     * @param request
     * @return
     */
    @RequestMapping("/getLoginUserInfo")
    public UserInfo getLoginUserInfo(HttpServletRequest request) {
        log.info("获取用户信息...");
        //获取 token
        String token = request.getHeader(Constants.REQUEST_HEADER_TOKEN);
        //从 token 中获取登录的用户的 id
        Integer userId = JwtUtils.getIdByToken(token);
        //用户未登录
        if (userId == null) return null;
        UserInfo userInfo = userInfoService.selectById(userId);
        return userInfo;
    }

    /**
     * 根据博客 id 获取作者信息
     */
    @RequestMapping("/getAuthorInfo")
    public UserInfo getAuthorInfo(Integer blogId) {
        if(blogId <= 0) return null;
        UserInfo userInfo = userInfoService.getAuthorInfo(blogId);
        return userInfo;
    }
}
